const express=require('express');
const app=express();
const mysql=require('mysql');
const db=mysql.createConnection({
    host:'localhost',
    port:'3306',
    user:'root',
    password:'123456',
    database:'fooddb'
    });
    app.use(express.json());
    app.use(express.urlencoded({extended:true}));

    //查
    app.post('/text',(req,res)=>{
        let sql='select * from t_types';
        db.query(sql,(err,result)=>{
            if(err){
                console.log(err);
                res.send('error');
            }else{
                res.send(result);
            }
        })
    })
    //删
    app.post('/delete',(req,res)=>{
        let id=req.body.id;
        let sql='delete from t_types where id=?';
        db.query(sql,[req.body.id],(err,result)=>{
            if(err){
                console.log(err);
                res.send('error');
            }else{
                res.send('删除成功');
            }
        })
    })
    //改
    app.post('/update',(req,res)=>{
        let sql='update t_types set typename=?,icon=? where id=?';
        db.query(sql,[req.body.typename,req.body.icon,req.body.id],(err,result)=>{
            if(err){
                console.log(err);
                res.send('error');
            }else{
                res.send('修改成功');
            }
        })
    })
    //增
    app.post('/add',(req,res)=>{
        let sql='insert into t_types(typename,icon) values(?,?)';
        db.query(sql,[req.body.typename,req.body.icon],(err,result)=>{
            if(err){
                console.log(err);
                res.send('error');
            }else{
                res.send('添加成功');
            }
        })
    })

    app.listen(3000,()=>{
        console.log('server is running on port 3000');
         });